import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { Toast } from "vant";
import axios from "axios";
Vue.config.productionTip = false
// 配置请求的根路径
axios.defaults.baseURL = process.env.VUE_APP_BASEURL;
console.log(process.env.VUE_APP_BASEURL);
Vue.prototype.$http = axios;
Vue.prototype.$https = axios;
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
axios.interceptors.request.use((config) => {
  config.headers.Authorization = window.localStorage.getItem("token");
  // 在最后必须 return config
  return config;
});

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    Toast.clear();
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          Toast(error.response.data.msg);
          router.replace({
            path: "/login",
            query: {
              redirect: router.currentRoute.fullPath,
            },
          });
      }
    }
    return Promise.reject(error.response.data); // 返回接口返回的错误信息
  }
);
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
